//
//  DLPasswordInputVC.m
//  AllPass
//
//  Created by apple on 2021/11/2.
//

#import "DLPasswordInputVC.h"
#import "BRPickerView.h"
@interface DLPasswordInputVC ()
@property (weak, nonatomic) IBOutlet UITextField *pswTF;
@property (weak, nonatomic) IBOutlet UILabel *keyFileNameLab;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topHegiht;
@property(nonatomic,assign)BOOL isRemPsw;
@property(nonatomic,copy)NSString * keyFileName;
@end

@implementation DLPasswordInputVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.topHegiht.constant = kTopHeight + 20;
    self.view.backgroundColor = UnderLineColor;
    self.leftBtnImage = @"navigationbar_back_image";
    self.myTitle = self.dbName;
}
- (void)backClick{
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (IBAction)choseKeyFieldClick:(id)sender {
    NSString *documentsDirectory = [Mytools documentsDirectory];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSArray *dirContents = [fileManager contentsOfDirectoryAtPath:documentsDirectory error:nil];
    NSMutableArray *files = [[NSMutableArray alloc] init];
    for (NSString *file in dirContents) {
        NSString *path = [documentsDirectory stringByAppendingPathComponent:file];
        BOOL dir = NO;
        [fileManager fileExistsAtPath:path isDirectory:&dir];
        if (!dir) {
            [files addObject:file];
        }
    }
    [files sortUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
    NSArray *keyFilenames = [files filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"!((self ENDSWITH[c] '.kdb') OR (self ENDSWITH[c] '.kdbx'))"]];
    [BRStringPickerView showPickerWithTitle:NSLocalizedString(@"KeyFiles", nil) dataSourceArr:keyFilenames selectIndex:0 resultBlock:^(BRResultModel * _Nullable resultModel) {
        self.keyFileNameLab.text = resultModel.value;
        self.keyFileName = resultModel.value;
    }];
}
- (IBAction)rememberPswClick:(UIButton *)sender {
    sender.selected = !sender.selected;
    self.isRemPsw = sender.isSelected;
}
- (IBAction)doneClick:(id)sender {
    NSString *documentsDirectory = [Mytools documentsDirectory];
    NSString *path = [documentsDirectory stringByAppendingPathComponent:self.dbName];
    if (self.pswTF.text.length == 0) {
        if (self.keyFileName.length == 0) {
            XHQHUDErrorText(NSLocalizedString(@"Password should not be empty", nil));
        }else{
            @try {
                NSString *keyFilePath = [documentsDirectory stringByAppendingPathComponent:self.keyFileName];
                if (self.isRemPsw) {
                    NSMutableDictionary * dic = [NSMutableDictionary new];
                    NSDictionary * enterDic = [DLUserDefault userDefaultsModel].eneterPswDic;
                    [dic addEntriesFromDictionary:enterDic];
                    [dic setObject:self.keyFileName forKey:self.dbName];
                    [DLUserDefault userDefaultsModel].eneterPswDic = dic.copy;
                }
                [self openDataBase:path password:nil keyfile:keyFilePath];
            } @catch (NSException *exception) {
                DLLog(@"%@", exception);
                XHQHUDErrorText(NSLocalizedString(exception.reason, nil));
            }
        }
    }else{
        if (self.isRemPsw) {
            NSMutableDictionary * dic = [NSMutableDictionary new];
            NSDictionary * enterDic = [DLUserDefault userDefaultsModel].eneterPswDic;
            [dic addEntriesFromDictionary:enterDic];
            [dic setObject:self.pswTF.text forKey:self.dbName];
            [DLUserDefault userDefaultsModel].eneterPswDic = dic.copy;
        }
        @try {
            // Open the database
            [self openDataBase:path password:self.pswTF.text keyfile:nil];
        } @catch (NSException *exception) {
            DLLog(@"%@", exception);
            XHQHUDErrorText(NSLocalizedString(exception.reason, nil));
        }
    }
}
-(void)openDataBase:(NSString*)path password:(NSString*)psw keyfile:(NSString*)kf{
    DatabaseDocument *dd = [[DatabaseDocument alloc] initWithFilename:path password:psw keyFile:kf];
    if (dd.kdbTree==nil) {//若报错就移除对应的要保存的密码
        NSMutableDictionary * dic = [NSMutableDictionary new];
        NSDictionary * enterDic = [DLUserDefault userDefaultsModel].eneterPswDic;
        [dic addEntriesFromDictionary:enterDic];
        [dic removeObjectForKey:self.dbName];
        [DLUserDefault userDefaultsModel].eneterPswDic = dic.copy;
    }
    [self dismissViewControllerAnimated:YES completion:^{
        if (self.enterBlock) {
            self.enterBlock(dd);
        }
    }];
}
@end
